
import 'dart:convert';
import 'dart:math';

import 'package:bot_toast/bot_toast.dart';
import 'package:exams_app/gen_a/A.dart';
import 'package:exams_app/home_module/live_module/live_logic.dart';
import 'package:exams_app/net/Address.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:exams_app/home_module/live_module/chat_page.dart';
import 'package:exams_app/home_module/live_module/jiangshi_page.dart';
import 'student_page.dart';
import 'package:get/get.dart';

import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:web_socket_channel/status.dart' as status;
import 'dart:convert' as convert;

import 'package:fijkplayer/fijkplayer.dart';
import 'package:wakelock/wakelock.dart';

class LivePages extends StatefulWidget {

  //
  var liveid;
  //
  // var liveURL;
  //
  // var json;


  LivePages(this.liveid);


  @override
  _LivePagesState createState() => _LivePagesState();
}


class _LivePagesState extends State<LivePages> with SingleTickerProviderStateMixin  {


  WebSocketChannel channel;



  List<MyMessage> mymsgList = List();

  var name;
  var uid;
  TabController _controller;
  var maxNumjson;


  var countlist = List();

  var u_count =0;

  var jiantingjson;


  bool isShowPlay = false;
  AnimationController _animationControlleron;
  Animation _animation;

  final FijkPlayer player = FijkPlayer();


  Future requestDataWithLive(var liveid)async{

    var  params = {
      'live_id':liveid,
    };
    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).
    postModel(Address.getattt,function_name:'_api_one',model:'res.live',params:params );
    Map _json = jsonDecode(result);
    maxNumjson = _json;

    print('================= ${result}');


    return maxNumjson;
  }


  /// 连接 socket

  void connectSocket()async{


    name = await PersistentStorage().getStorage('name');
    uid = await PersistentStorage().getStorage('uid');

    Map<String, dynamic> b =  convert.jsonDecode('''
        {"uid":${await PersistentStorage().getStorage('uid')},"name":"app-${await PersistentStorage().getStorage('name')}"}
        ''');

    // Map<String, dynamic> b =  convert.jsonDecode('''{"uid":${await PersistentStorage().getStorage('uid')},"name":"${await PersistentStorage().getStorage('name')}"}''');
    // Map<String, dynamic> c =  convert.jsonDecode('''{"uid":${await PersistentStorage().getStorage('uid')},"name":"${await PersistentStorage().getStorage('name')}"},"msgtype":1''');

    countlist.insert(0, b);

    channel.sink.add(
      convert.jsonEncode(b),
    );




    setState(() {

    });
  }

  @override
  void dispose() {
    print('断开了链接');
    channel.sink.close();
    player.release();
    super.dispose();

  }


  @override
  void initState() {
    List useridArr = List();

    Wakelock.enable();

    requestDataWithLive(widget.liveid).then((value)async{
      if(value['data'][0]['is_users_limit']==true){
        List user_list = value['data'][0]['user_list'];
        if(user_list.length==0){
          Get.back();
          BotToast.showText(text: '暂未报名,已自动退出');
          return;
        }

        for(int i = 0;i<user_list.length;i++){

          var s = user_list[i]['user_id'];
          useridArr.add(s);
          print('${useridArr}');

          // if(useridArr.contains(await PersistentStorage().getStorage('uid'))){
          //       print('跳出for循环');
          //       break;
          // }else{
          //     print('没有跳出');
          //     Future.delayed(Duration(milliseconds: 500), ()async {
          //       Get.back();
          //       BotToast.showText(text: '暂未报名,已自动退出');
          //     });
          //   }

          // if(await PersistentStorage().getStorage('uid') == user_list[i]['user_id']){
          //     print('报名人员对比 === ${await PersistentStorage().getStorage('uid')},${user_list[i]['user_id']}');
          //    // Get.back();
          //     print('跳出for循环');
          //     break;
          // }else{
          //   print('没有跳出');
          //   Future.delayed(Duration(milliseconds: 500), ()async {
          //     Get.back();
          //     BotToast.showText(text: '暂未报名,已自动退出');
          //   });
          // }
        }
        if(useridArr.contains(await PersistentStorage().getStorage('uid'))){

          return;
        }else{
          print('没有跳出');
          Future.delayed(Duration(milliseconds: 500), ()async {
            Get.back();
            BotToast.showText(text: '暂未报名,已自动退出');
          });
        }


      }else{
        /// 未开启限制+


      }
    }).whenComplete(() {



    });


    Map<String, dynamic> headers = new Map();
    headers['origin'] = 'wss://x.xx.com:443/ws/'; // 加上一个origin，防止被拦截

    channel = IOWebSocketChannel.connect(
        'ws://36.153.159.19:7060/ws',
        // 可以设置请求头
        headers: headers
    );



    // player.setDataSource('http://www.zyfchina.com/templates/default/vedio/zyf2021.mp4', autoPlay: false,showCover: true);


    Future.delayed(Duration(milliseconds: 3000), () {

      print('开启拉流');
      player.setDataSource('rtmp://36.153.159.19:1935/live/888zhibo', autoPlay: true,);

    });

    _controller = TabController(length: 3, vsync: this);


    // channel = IOWebSocketChannel.connect(Address.wsHost);

    mymsgList.insert(0, MyMessage('','',''));

    connectSocket();





    channel.stream.listen((message) {

      var b =  convert.jsonDecode(message);

      print('--------------------------${b}');






      if(b['msgtype']==2){

          mymsgList.insert(0, MyMessage(b['content'], b['name'], b['uid']));

      }else{




        u_count = b['UserList'].length;
        jiantingjson = b;

      }


      setState(() {

      });

    });

    Future.delayed(Duration(milliseconds: 500), () {


      requestDataWithLive(widget.liveid).then((value)async {

        if(value['data'][0]['is_umber_limit']==true){

          if(value['data'][0]['max_num'] < jiantingjson['number']){
            BotToast.showText(text: '已超过最大人数${value['data'][0]['max_num']}人,自动退出');
            for(int i = 0;i<jiantingjson['UserList'].length;i++){
              if(jiantingjson['UserList'][i]['uid'] == await PersistentStorage().getStorage('uid')&&jiantingjson['UserList'][i]['name']=='app-${await PersistentStorage().getStorage('name')}'){
                Get.back();
                return;
              }else{


              }
            }

          }
        }else{


        }
      });

    });



    // TODO: implement initState
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('直播间'),
      ),
      body: Column(
        children: [
          Container(
            child: GestureDetector(
              onTap: (){

              },
              child: FijkView(
                // fsFit: FijkFit.contain,
                fit: FijkFit.fill,
                // panelBuilder: fijkPanel2Builder(
                //
                // ),

                cover: AssetImage(A.assets_z1),
                color: Colors.white,
                player: player,
                panelBuilder: (FijkPlayer player, FijkData data, BuildContext context, Size viewSize, Rect texturePos) {
                  return Visibility(
                    visible: true,
                      child: CustomFijkPanel(
                      player: player,
                      buildContext: context,
                      viewSize: viewSize,
                      texturePos: texturePos)
                  );
                },
              ),
            ),
            height: 225,
            color: Colors.black,
          ),
          Container(

            width: Get.width,
            child: TabBar(
              isScrollable: true,
              controller: _controller,
              labelStyle: TextStyle(
                  fontSize: 14,
                  color: HexColor('#567BFD'),
                  fontWeight: FontWeight.w600),
              labelColor: HexColor('#567BFD'),
              unselectedLabelStyle:
              TextStyle(fontSize: 14, color: HexColor('567BFD')),
              unselectedLabelColor: HexColor('#999999'),
              // indicatorSize: TabBarIndicatorSize.label,
              indicator: MyUnderlineTabIndicator(
                  borderSide:
                  BorderSide(width: 2.0, color: HexColor('#567BFD'))),
              indicatorColor: HexColor('#567BFD'),
              // indicator: const BoxDecoration(),

              tabs: [
                Tab(
                  text: '聊天',
                ),
                Tab(
                  text: '讲师',
                ),
                Tab(
                  text: '在线人数(${u_count})',
                ),
              ],
            ),
          ),
          Expanded(
            child: TabBarView(
              controller: _controller,
              children: [
                ChatPage(channel,mymsgList),
                JiangShiPage(),
                StudentPage(jiantingjson),
              ],
            ),
          )
        ],
      ),
    );
  }
}

class CustomFijkPanel extends StatefulWidget {
  final FijkPlayer player;
  final BuildContext buildContext;
  final Size viewSize;
  final Rect texturePos;

  const CustomFijkPanel({
    @required this.player,
    this.buildContext,
    this.viewSize,
    this.texturePos,
  });

  @override
  _CustomFijkPanelState createState() => _CustomFijkPanelState();
}

class _CustomFijkPanelState extends State<CustomFijkPanel> {

  FijkPlayer get player => widget.player;

  bool _playing = true;

  bool isShow = true;

  @override
  void initState() {
    super.initState();

    widget.player.addListener(_playerValueChanged);
  }

  void _playerValueChanged() {

    FijkValue value = player.value;




    bool playing = (value.state == FijkState.started);

    _playing = playing;

    if(player.state ==FijkState.error||player.state ==FijkState.idle){
      widget.player.reset();
      BotToast.showText(text: '网络连接出错,请刷新重试');
      BotToast.closeAllLoading();

      // print('网络状态发生改变');
      // widget.player.setDataSource('rtmp://36.153.159.19:1935/live/888zhibo', autoPlay: true,);
      // widget.player.start();
    }if(player.state == FijkState.asyncPreparing){
      BotToast.showText(text: '播放就绪');
    }

    if(player.state == FijkState.started){
      print('正在播放');
      BotToast.closeAllLoading();
    }


  }

  @override
  Widget build(BuildContext context) {
    Rect rect = Rect.fromLTRB(
        max(0.0, widget.texturePos.left),
        max(0.0, widget.texturePos.top),
        min(widget.viewSize.width, widget.texturePos.right),
        min(widget.viewSize.height, widget.texturePos.bottom));

    return  GestureDetector(
      onTap: (){
        print('123');
        isShow=!isShow;
        setState(() {

        });
      },
      child: Container(
        // rect: rect,
        color: Colors.transparent,
        width: double.infinity,
        height: double.infinity,
        child: Container(
            alignment: Alignment.bottomLeft,
            child:Visibility(
              visible: isShow,
              child: Container(
                color: Colors.black12,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        IconButton(
                          icon: Icon(
                            _playing==true ? Icons.pause : Icons.play_arrow,
                            color: Colors.white,
                          ),
                          onPressed: () {

                            print('播放暂停开始,${_playing}');
                            if(_playing==true){
                              widget.player.pause();
                              _playing = false;
                            }else{
                              widget.player.start();
                              _playing=true;
                            }

                            setState(() {

                            });
                            // if(player.value.fullScreen==false){
                            //   player.enterFullScreen();
                            // }else{
                            //   player.exitFullScreen();
                            // }
                            //
                            // player.reset();
                            // player.setDataSource('rtmp://36.153.159.19:1935/live/888zhibo', autoPlay: true,);

                            // _playing ? widget.player.pause() : widget.player.start();
                          },
                        ),
                        IconButton(
                          icon: Icon(Icons.refresh,color: Colors.white,),
                          onPressed: () {


                            BotToast.showLoading(allowClick: true,clickClose: true,duration: Duration(milliseconds: 500));
                            //
                            // if(_playing==true){
                            //   BotToast.closeAllLoading();
                            //   BotToast.showText(text: '正在播放');
                            // }


                            widget.player.setDataSource('rtmp://36.153.159.19:1935/live/888zhibo', autoPlay: true,);
                            widget.player.start();
                          },
                        ),
                      ],
                    ),
                    IconButton(
                      icon: Icon(
                        Icons.fullscreen,
                        color: Colors.white,
                      ),
                      onPressed: () {
                        if(player.value.fullScreen==false){

                          player.enterFullScreen();
                        }else{
                          player.exitFullScreen();
                        }
                        setState(() {

                        });

                        // _playing ? widget.player.pause() : widget.player.start();
                      },
                    )
                  ],
                ),
              ),
            )
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    player.removeListener(_playerValueChanged);
  }
}
